var Ajax = function (vue) {


    var axios = vue.$Axios;
    var getItem = vue.$getItem;
    var md5 = vue.$md5;

    var infolist = {};


    var userdb = {
        set: function (row, callback) {
            infolist[row.etag] = {
                value: typeof row.value == 'string' ? JSON.parse(row.value) : row.value,
                timedb: new Date().getTime(),
                lms: row.lms,
                key: row.key,
                etag: row.etag
            }
            callback()
        },
        get: function (key, callback) {
            var obj = infolist[key];
            if (obj) {
                callback(obj.value, obj.etag, obj.lms)
            } else {
                callback()
            }
        }
    };
    if (window.indexedDB) {
        var clint_indexedDB = require('./clint_db');
        userdb = new clint_indexedDB();
    } else if (window.openDatabase) {
        var clint_openDatabase = require('./clintdb');
        userdb = new clint_openDatabase(function () {});
    }


    var getkey = function (val) {
        var _val = ""
        if (typeof val == 'string') {

            _val = val;
        } else if (typeof val == 'object' && val instanceof Array) {
            _val = "";
            val.sort().forEach(function (key) {
                var _type = typeof key;
                if (_type == 'string' || _type == 'number' || _type == 'boolean') {
                    _val = _val + '/' + key;
                }
            });

        } else if (typeof val == 'object') {
            _val = "";
            Object.keys(val).sort().forEach(function (key) {
                var _type = typeof val[key];
                if (_type == 'string' || _type == 'number' || _type == 'boolean') {
                    _val = _val + '/' + val[key]
                }
            });
        }
        var etag = _val ? md5(_val) : md5("xrc");
        return etag.toLocaleUpperCase();
    }

    return function (url, data, method) {


        var _ajax = function (url, data, method) {

            console.log(url);


            console.log(new Date().getTime());

            var axiosThen = function () {};
            var axiosCatch = function () {};
            this.then = function (_then) {
                axiosThen = _then
                return self;
            }
            this.catch = function (_catch) {
                axiosCatch = _catch
                return self;
            }

            //token_key

            var self = this;
            var initdb = function (headers, db) {

                console.log(headers);
                var timeout = 3000 * 9;
                var NetworkRequest = false;

                axios({
                    method: method === 'get' ? 'get' : 'post',
                    url: url,
                    timeout: timeout,
                    headers: typeof headers == 'object' ? headers : {},
                    data: data
                }).then(function (response) {
                    if (response.data) {
                        if (!NetworkRequest) {

                            NetworkRequest = true;
                            var data = response.data;
                            var etag = response.headers.etag;


                            if (etag && etag.indexOf('W/ms-') > -1 && (data.error == null || data.error == 0)) {
                                var lastmodified = '-';
                                if (response.headers['last-modified']) {
                                    lastmodified = response.headers['last-modified'];
                                }
                                var key = (db == null ? headers : db.key);
                                var etag = etag.replace('W/ms-', "");
                                userdb.set({
                                    lms: lastmodified,
                                    key: key,
                                    etag: etag,
                                    value: data
                                }, function (row_id, error) {

                                    console.log('save local db etag=>' + etag);

                                    axiosThen(response)

                                });
                            } else if (data.error == 1 && window.location.hash.replace("#/", "").replace("#", "").toLocaleLowerCase() != 'login') {
                                vue.$router.push('/login');
                            } else {
                                axiosThen(response)
                            }
                        }
                    }
                }).catch(function (error) {
                    if (!NetworkRequest) {
                        NetworkRequest = true;
                        if (error.request && error.request.status == 304 && db) {

                            setTimeout(function () {
                                axiosThen({
                                    data: db.data
                                })
                            }, 50)
                            console.log(error.request.status)
                            return /// Promise.reject(error);
                        } else {
                            axiosCatch(error)

                            /* axiosThen({
                                 data: {
                                     error: 1001
                                 }
                             })*/

                        }
                    }
                });

            };


            var key = getkey(Object.assign({
                url: url,
                token: getItem("user_token")
            }, data));
            userdb.get(key, function (val, etag, lms) {
                if (val) {

                    console.log('local db etag=>' + etag);

                    var headers = {
                        "cache-control": "private, must-revalidate",
                        "if-none-match": 'W/ms-' + etag
                    };
                    if (lms != '-') {
                        headers['if-modified-since'] = lms;
                    };
                    initdb(headers, {
                        key: key,
                        data: val
                    });
                } else {
                    console.log('not local db')
                    initdb(key)
                }
            });
        }
        return new _ajax(url, data, method);
    }
};

module.exports = Ajax;